package com.krius;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;

/**
 * Create By IntelliJ IDEA
 *
 * @Author: jsonor
 * @Create-Time: 2017/9/14 11:10
 * @Description: DBCP连接池的使用方式
 */
public class Dbcp {

  public static void main(String[] args) {
    Properties props = new Properties();
    InputStream stream = Dbcp.class.getClassLoader()
        .getResourceAsStream("dbcp.properties");
    Connection cn = null;

    try {
      props.load(stream);
      DataSource ds = BasicDataSourceFactory.createDataSource(props);
      cn = ds.getConnection();
      cn.prepareStatement("select * from user");
    } catch (IOException e) {
      throw new ExceptionInInitializerError(e);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (cn != null) {
        try {
          // close 实际不是关闭
          cn.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }

  }

  /**
   * 使用硬编码方式配置DBCP连接池
   */
  private static void HardEncoder() {
    // 连接池
    BasicDataSource dbSource = new BasicDataSource();
    // 配置连接池的信息
    // Java Bean
    // set + 字段首字母大写 + 后面的字母小写
    dbSource.setDriverClassName("com.mysql.jdbc.Driver");
    dbSource.setUrl("jdbc:mysql:///test");
    dbSource.setUsername("root");
    dbSource.setPassword("123456789");

    // 设置初始化的的连接池的容量
    dbSource.setInitialSize(10);
    dbSource.setMaxActive(5);
    dbSource.setMaxIdle(4);

    long startTime = System.currentTimeMillis();
    Connection cn = null;
    try {
      cn = dbSource.getConnection();
      cn.prepareStatement("select * from user");

      System.out.println("cost time = " + (System.currentTimeMillis() - startTime) + " ms");
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      if (cn != null) {
        try {
          cn.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
  }
}
